rm(list=ls())

# 4_GenerateMaps.R
# Goal: Script to make maps/figures
# B.Lee
# Date Created: 2024-02-08
# Last Updated: 2024-08-26 \\ tja

# set up directories

# uncomment the line below and add working directory path between the quotation marks
# master_directory = "ADD WORKING DIRECTORY HERE/"

data_folder = paste0(master_directory,"Data/")
do_folder = paste0(master_directory,"Do/")
results_folder = paste0(master_directory,"Results/")
charts_folder = paste0(master_directory,"Charts/")

# Load libraries
library(tidyverse)
library(haven)
library(ggplot2)
library(usmap)
library(sf)
library(patchwork)

#elections_master <- read_dta(paste0(data_folder,"Processing/state_elections_panel_df_recoded_normvote_updated.dta"))
elections_master <- read_dta(paste0(data_folder,"Processing/state_elections_panel_df5_20240709.dta"))


elections_master1 <- elections_master %>%
  mutate(total_aid_per_cap = total_1k_muni_aid_per_resident*1000) %>%
  filter(insample == 1 & year >= 2020)

# 1) Heat map - aid per capita -----------------------------------------------

## Option 1: In USD thousands ---------------
aid_map_1k <- plot_usmap(data = elections_master1 %>%
                        mutate(fips = sfips),
                      values = "total_1k_muni_aid_per_resident",
                      regions = "states") + 
  scale_fill_continuous(low = "white", high = "blue",
                        name = "Total Aid\nper Capita\n(USD thousands)", 
                        limits=c(min(elections_master1$total_1k_muni_aid_per_resident,na.rm=TRUE),max(elections_master1$total_1k_muni_aid_per_resident,na.rm=TRUE)),
                        breaks=c(min(elections_master1$total_1k_muni_aid_per_resident,na.rm=TRUE),2,3,4,5,max(elections_master1$total_1k_muni_aid_per_resident,na.rm=TRUE)),
                        labels=scales::dollar,
                        guide = guide_colorbar(frame.colour = "black", ticks.colour = "black",barheight=unit(10,'cm'))) +
  theme(panel.background = element_rect(color = "white"),
        text = element_text(size = 25),
        legend.position =  c(.97, 0.05),
        plot.title = element_text(hjust=0.5))

print(aid_map_1k)
ggsave(paste0(charts_folder,"aid_map_1k_20240715.jpeg"),aid_map_1k,width=25,height=10,units="in")

## Option 2: In USD ---------------------
aid_map <- plot_usmap(data = elections_master1 %>%
                        mutate(fips = sfips),
                      values = "total_aid_per_cap",
                      regions = "states") + 
  scale_fill_continuous(low = "white", high = "blue",
                        name = "Total Aid\nper Capita", 
                        limits = c(min(elections_master1$total_aid_per_cap, na.rm = TRUE), 
                                   max(elections_master1$total_aid_per_cap, na.rm = TRUE)),
                        breaks = c(2000, 3000, 4000, 5000),  # Exclude min and max values here
                        labels = scales::dollar_format(accuracy = 1),
                        guide = guide_colorbar(frame.colour = "black", 
                                               ticks.colour = "black",
                                               barheight = unit(10, 'cm'),
                                               barwidth = unit(0.5, 'cm'),
                                               title.position = "top",
                                               title.hjust = 0.5,
                                               title.vjust = 4)) + 
  theme(panel.background = element_rect(color = "white"),
        text = element_text(size = 35),
        legend.position = "right",  
        plot.title = element_text(hjust = 0.5),
        legend.title = element_text(size = 18, face = "bold"),
        legend.text = element_text(size = 16))

print(aid_map)
ggsave(paste0(charts_folder, "aid_map_20240827.pdf"), aid_map, width = 25, height = 10, units = "in")

# 1) Heat map - incumbent share per capita -----------------------------------------------

# Average for Georgia in 2020
ga_2020_avg <- elections_master1 %>%
  filter(office == "senate" & year == 2020 & state == "GA") %>%
  summarise(incumbent_vote_share_top2 = mean(incumbent_vote_share_top2, na.rm = TRUE)) %>%
  pull(incumbent_vote_share_top2)

# Replace GA's incumbent_vote_share_top2 with the average in 2020
elections_master1 <- elections_master1 %>%
  mutate(incumbent_vote_share_top2 = ifelse(office == "senate" & year == 2020 & state == "GA", 
                                            ga_2020_avg, 
                                            incumbent_vote_share_top2))

# Average for Oklahoma in 2022
ok_2022_avg <- elections_master1 %>%
  filter(office == "senate" & year == 2022 & state == "OK") %>%
  summarise(incumbent_vote_share_top2 = mean(incumbent_vote_share_top2, na.rm = TRUE)) %>%
  pull(incumbent_vote_share_top2)

# Replace OK's incumbent_vote_share_top2 with the average in 2022
elections_master1 <- elections_master1 %>%
  mutate(incumbent_vote_share_top2 = ifelse(office == "senate" & year == 2022 & state == "OK", 
                                            ok_2022_avg, 
                                            incumbent_vote_share_top2))

## Incumbent share for 2020 senate races ---------------
us_states <- as.data.frame(us_map(regions = "states")) %>%
  select(abbr, geom)

inc_senate_data <- elections_master1 %>%
  filter(office == "senate" & year == 2020)

inc_map_senate20 <- plot_usmap(data = inc_senate_data %>%
                                 mutate(fips = sfips),
                               values = "incumbent_vote_share_top2",
                               regions = "states") + 
  scale_fill_continuous(low = "white", high = "red",
                        name = NULL,
                        limits = c(floor(min(inc_senate_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10, 
                                   ceiling(max(inc_senate_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10),
                        breaks = seq(floor(min(inc_senate_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10, 
                                     ceiling(max(inc_senate_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10, by = 10),
                        labels = scales::label_percent(accuracy = 1, scale = 1, suffix = "%"),
                        guide = guide_colorbar(frame.colour = "black", 
                                               ticks.colour = "black",
                                               barheight = unit(20, 'cm'),
                                               barwidth = unit(0.5, 'cm'),
                                               title.position = "top",
                                               title.hjust = 0.5,
                                               title.vjust = 1)) +  
  theme(panel.background = element_rect(color = "white"),
        text = element_text(size = 35),
        legend.position = "right",
        plot.title = element_text(hjust = 0.5),
        legend.text = element_text(size = 35))

inc_map_senate20
ggsave(paste0(charts_folder, "inc_map_2020senate_20240827.pdf"), inc_map_senate20, width = 25, height = 10, units = "in")

## Incumbent share for 2022 senate races ---------------

inc_senate22_data <- elections_master1 %>%
  filter(office == "senate" & year == 2022)

inc_map_senate22 <- plot_usmap(data = inc_senate22_data %>%
                                 mutate(fips = sfips),
                               values = "incumbent_vote_share_top2",
                               regions = "states") + 
  scale_fill_continuous(low = "white", high = "red",
                        name = NULL, 
                        limits = c(floor(min(inc_senate22_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10, 
                                   ceiling(max(inc_senate22_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10),
                        breaks = seq(floor(min(inc_senate22_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10, 
                                     ceiling(max(inc_senate22_data$incumbent_vote_share_top2, na.rm = TRUE) / 10) * 10, by = 10),
                        labels = scales::label_percent(accuracy = 1, scale = 1, suffix = "%"),
                        guide = guide_colorbar(frame.colour = "black", 
                                               ticks.colour = "black",
                                               barheight = unit(20, 'cm'),
                                               barwidth = unit(0.5, 'cm'),
                                               title.position = "top",
                                               title.hjust = 0.5,
                                               title.vjust = 1)) + 
  theme(panel.background = element_rect(color = "white"),
        text = element_text(size = 35),
        legend.position = "right",
        plot.title = element_text(hjust = 0.5),
        legend.text = element_text(size = 35))

print(inc_map_senate22)
ggsave(paste0(charts_folder, "inc_map_2022senate_20240827.pdf"), inc_map_senate22, width = 25, height = 10, units = "in")

## Incumbent share for gubernatorial races ---------------

inc_gub_data <- elections_master1 %>%
  filter(office == "gub") %>%
  group_by(state) %>%
  mutate(avg_inc_vs = mean(incumbent_vote_share_top2))

inc_map_gub <- plot_usmap(data = inc_gub_data %>%
                            mutate(fips = sfips),
                          values = "avg_inc_vs",
                          regions = "states") + 
  scale_fill_continuous(low = "white", high = "red",
                        name = NULL, 
                        limits = c(floor(min(inc_gub_data$avg_inc_vs, na.rm = TRUE) / 10) * 10, 
                                   ceiling(max(inc_gub_data$avg_inc_vs, na.rm = TRUE) / 10) * 10),
                        breaks = seq(floor(min(inc_gub_data$avg_inc_vs, na.rm = TRUE) / 10) * 10, 
                                     ceiling(max(inc_gub_data$avg_inc_vs, na.rm = TRUE) / 10) * 10, by = 10),
                        labels = scales::label_percent(accuracy = 1, scale = 1, suffix = "%"),
                        guide = guide_colorbar(frame.colour = "black", 
                                               ticks.colour = "black",
                                               barheight = unit(20, 'cm'),
                                               barwidth = unit(0.5, 'cm'),
                                               title.position = "top",
                                               title.hjust = 0.5,
                                               title.vjust = 1)) + 
  theme(panel.background = element_rect(color = "white"),
        text = element_text(size = 35),
        legend.position = "right",
        plot.title = element_text(hjust = 0.5),
        legend.text = element_text(size = 35))

inc_map_gub
ggsave(paste0(charts_folder, "inc_map_gub_20240827.pdf"), inc_map_gub, width = 25, height = 10, units = "in")

## Incumbent share for house-at-large races ---------------

inc_house_data <- elections_master1 %>%
  filter(office == "house") %>%
  group_by(state) %>%
  summarize(avg_inc_vs = mean(incumbent_vote_share_top2),
            sfips = mean(sfips)) %>%
  ungroup()

inc_map_house <- plot_usmap(data = inc_house_data %>%
                              mutate(fips = sfips),
                            values = "avg_inc_vs",
                            regions = "states") + 
  scale_fill_continuous(low = "white", high = "red",
                        name = NULL, 
                        limits = c(floor(min(inc_house_data$avg_inc_vs, na.rm = TRUE) / 10) * 10, 
                                   ceiling(max(inc_house_data$avg_inc_vs, na.rm = TRUE) / 10) * 10),
                        breaks = seq(floor(min(inc_house_data$avg_inc_vs, na.rm = TRUE) / 10) * 10, 
                                     ceiling(max(inc_house_data$avg_inc_vs, na.rm = TRUE) / 10) * 10, by = 10),
                        labels = scales::label_percent(accuracy = 1, scale = 1, suffix = "%"),
                        guide = guide_colorbar(frame.colour = "black", 
                                               ticks.colour = "black",
                                               barheight = unit(20, 'cm'),
                                               barwidth = unit(0.5, 'cm'),
                                               title.position = "top",
                                               title.hjust = 0.5,
                                               title.vjust = 1)) + 
  theme(panel.background = element_rect(color = "white"),
        text = element_text(size = 35),
        legend.position = "right",
        plot.title = element_text(hjust = 0.5),
        legend.text = element_text(size = 35))

print(inc_map_house)
ggsave(paste0(charts_folder, "inc_map_house_20240827.pdf"), inc_map_house, width = 25, height = 10, units = "in")
